import express from "express";
const speech = require('@google-cloud/speech');
const request = require('request')
const fs = require("fs");
const path = require("path");

const app = express();
const port = 3000;

app.get("/", (req, res) => res.send("Hello World!"));
// process.on('uncaughtException', function (e) {
//     console.log(e);
// });
console.log("node to start")
//*** for speech-cloud
// Creates a client
const client = new speech.SpeechClient();
//创建文件夹目录
var dirPath = path.join(__dirname, "file");
if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath);
    console.log("文件夹创建成功");
} else {
    console.log("文件夹已存在");
}
app.get("/getText", (req, res) => {
    let filename = '13362037837.wav'
    let stream = fs.createWriteStream(path.join(dirPath, filename));
    request('https://media.textnow.com/?t=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IndvbGZlY3NnbyIsImtleSI6ImFlNDgzNGE0LWVmYjUtNGI5My1iOTcyLTgwYjNiMzA2YWMyMV8xNTY3MjA5MjU1OV8rMTMzNjIwMzc4Mzcud2F2In0.QNuhhBThpPjRd-UZYBIb-tic4gYS_d28llRsDhVWx20&h=ae4834a4-efb5-4b93-b972-80b3b306ac21_15672092559_%2B13362037837.wav', function (err, response, body) {
        /*
        response 响应信息的集合
        */
        // if (!err && response.statusCode == 200) {
        //  res.status(200).send(tbody)
        //  // console.log(body)
        // }
    }).pipe(stream).on("close",async function (err) {
            // console.log("文件[" + filename + "]下载完毕");
            
            // 执行转换
            let filePath = './src/file/'+filename;
            const file = fs.readFileSync(filePath);
            const audioBytes = file.toString('base64');
            const audio = {
                content: audioBytes,
            };
            // cmn-Hans-CN ：表示识别语言为中文普通话。常用的还有American English (en-US)、British English (en-GB)、日本語(ja-JP)、廣東話(yue-Hant-HK)。更多语言支持可以在Language Support | Google Cloud Speech API查询。
            const config = {
                encoding: 'LINEAR16',
                sampleRateHertz: 16000,
                languageCode: 'cmn-Hans-CN',
            };
            const request = {
                audio: audio,
                config: config,
            };
            const [response] = await client.recognize(request);
            const transcription = response.results.map((result) => {
                result.alternatives[0].transcript
            }).join('\n');
            console.log(`Transcription: ${transcription}`);

            res.status(200).send({
                log:"文件[" + filename + "]下载完毕",
                tran:transcription
            })
    });
});


app.listen(port, () => console.log(`Example app listening on port ${port}!`));